import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'

export async function GET(request: NextRequest) {
  try {
    // 验证用户身份
    const user = await getUserFromRequest(request)
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    console.log('📝 获取文案管理数据...')

    // 直接从 tiktok_videos 表查询所有视频数据，包含文案提取和改写信息
    const videos = await prisma.tikTokVideo.findMany({
      select: {
        id: true,
        videoId: true,
        title: true,
        author: true,
        createdAt: true,
        textExtractions: {
          select: {
            id: true,
            extractedText: true,
            method: true,
            status: true,
            createdAt: true
          },
          orderBy: {
            createdAt: 'desc'
          }
        },
        rewrittenTexts: {
          select: {
            id: true,
            originalText: true,
            rewrittenText: true,
            style: true,
            tone: true,
            length: true,
            requirements: true,
            createdAt: true
          },
          orderBy: {
            createdAt: 'desc'
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    })

    console.log(`📊 查询到 ${videos.length} 个视频记录`)

    // 只返回有有效文案的视频（已完成提取且文案不为空）
    const validVideos = videos.filter(video => {
      const hasValidExtraction = video.textExtractions.some(extraction =>
        extraction.status === 'completed' &&
        extraction.extractedText &&
        extraction.extractedText.trim().length > 0
      )
      return hasValidExtraction
    })

    console.log(`✅ 过滤后有 ${validVideos.length} 个有效文案的视频`)

    // 清理数据，只保留有效的文案提取记录
    const cleanedVideos = validVideos.map(video => ({
      ...video,
      textExtractions: video.textExtractions.filter(extraction =>
        extraction.status === 'completed' &&
        extraction.extractedText &&
        extraction.extractedText.trim().length > 0
      )
    }))

    return NextResponse.json({
      success: true,
      videos: cleanedVideos,
      total: cleanedVideos.length,
      statistics: {
        totalVideos: cleanedVideos.length,
        totalExtractions: cleanedVideos.reduce((sum, video) => sum + video.textExtractions.length, 0),
        totalRewrites: cleanedVideos.reduce((sum, video) => sum + video.rewrittenTexts.length, 0)
      }
    })

  } catch (error) {
    console.error('获取文案数据失败:', error)
    return NextResponse.json(
      { 
        error: '获取数据失败',
        details: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    )
  }
}
